package cn.wolfcode.luowowo.resolver;

import cn.wolfcode.luowowo.annotation.UserParam;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.domain.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * springmvc 参数解析器
 *
 * 把Userinfo 对象注入到 UserInfo 形式参数中
 */
public class UserInfoResolver implements HandlerMethodArgumentResolver{


    @Autowired
    private IUserInfoRedisService userInfoRedisService;


    // 第一个参数表示当请求映射方法参数为UserInfo 时,返回ture 表示支持注入
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        if(methodParameter.getParameterType() == UserInfo.class && methodParameter.hasParameterAnnotation(UserParam.class)){
            return true;
        }

        return false;
    }

    // 当上个方法返回true时,执行
    // 获取当前登录用户信息并注入到请求映射方法的形式参数UserInfo对象中
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        // 获取请求头中的token
        HttpServletRequest nativeRequest = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String token = nativeRequest.getHeader("token");
        UserInfo user = userInfoRedisService.getUserInfo(token);
        return user;
    }
}
